package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.domain.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 查询所有的菜品分类,并且排序
     * @return
     */
    @Override
    public List<Category> findAll() {
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("sort");
        List<Category> categoryList = categoryMapper.selectList(wrapper);
        return categoryList;
    }

    /**
     * 添加菜品分类
     * @param category
     */
    @Override
    public void save(Category category) {
        category.setId(IdUtil.getSnowflake(1,1).nextId());
        categoryMapper.insert(category);
    }

    /**
     * 修改菜品类信息
     * @param category
     */
    @Override
    public void update(Category category) {
        categoryMapper.updateById(category);
    }

    /**
     * 根据id删除菜品分类信息
     * @param id
     */
    @Override
    public void delete(Long id) {
        LambdaQueryWrapper<Dish> wrapper =new LambdaQueryWrapper<>();
        //根据id查询菜品分类下是否有菜品,有就不让删除
        wrapper.eq(id!=null,Dish::getCategoryId,id);
        Integer count = dishMapper.selectCount(wrapper);
        if (count>0){
            throw new CustomException("当前分类下关联了菜品,不能删除");
        }

        LambdaQueryWrapper<Setmeal> wrapper1 = new LambdaQueryWrapper<>();
        //根据id查询菜品分类下是否有套餐,有就不让删除
        wrapper1.eq(id!=null,Setmeal::getCategoryId,id);
        Integer count1 = setmealMapper.selectCount(wrapper1);
        if (count1>0){
            throw new CustomException("当前分类下关联了套餐,不能删除");
        }

        categoryMapper.deleteById(id);
    }

    /**
     * 菜品添加回显菜品分类名称
     * @param type
     * @return
     */
    @Override
    public List<Category> findList(Integer type) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(type!=null,Category::getType,type);
        List<Category> categoryList = categoryMapper.selectList(wrapper);
        return categoryList;
    }


}
